using System;
using System.IO;
using Lucene.Net.Analysis.Snowball;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Store;

namespace NopSolutions.NopCommerce.LuceneHelper
{
    public class IndexWriterWrapper : IDisposable
    {
        private IndexWriter _indexWriter;

        public IndexWriterWrapper(DirectoryInfo directory, bool recreate)
        {
            var fsDirectory = FSDirectory.Open(directory);
            var stopWords = Globals.StopWords();

            try
            {
                _indexWriter = new IndexWriter(fsDirectory, new SnowballAnalyzer("English", stopWords), recreate, IndexWriter.MaxFieldLength.UNLIMITED);
            }
            catch (FileNotFoundException)
            {
                //the index is set to not recreate, but unfortunately, it doesn't create the index if it isn't even built at all.
                //Since there are no previous documents that could be deleted, lets go ahead and recreate the index forcing the index to be created again.
                _indexWriter = new IndexWriter(fsDirectory, new SnowballAnalyzer("English", stopWords), true, IndexWriter.MaxFieldLength.UNLIMITED);
            }
            
        }

        //public IndexWriter Writer
        //{
        //    get { return _indexWriter; }
        //    set { _indexWriter = value; }
        //}

        public void AddDocument(Document document)
        {
            document.AddField("Const", "1");
            _indexWriter.AddDocument(document);
        }

        public void DeleteDocuments(Term term)
        {
            _indexWriter.DeleteDocuments(term);
        }

        public void DeleteDocuments(Query query)
        {
            _indexWriter.DeleteDocuments(query);
        }

        public void UpdateDocument(Term term, Document document)
        {
            _indexWriter.UpdateDocument(term, document);
        }

        public void Dispose()
        {
            _indexWriter.Optimize();
            _indexWriter.Commit();
            _indexWriter.Close(true);
        }
    }
}
